package com.geeguo.ebuilder.core.security.aspect;

import com.geeguo.ebuilder.core.security.annotation.RequiresLogin;
import com.geeguo.ebuilder.core.security.annotation.RequiresPermissions;
import com.geeguo.ebuilder.core.security.annotation.RequiresRoles;
import com.geeguo.ebuilder.core.security.model.BaseLoginUser;
import com.geeguo.ebuilder.core.security.utils.AuthHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * 注解鉴权
 */
@Aspect
@Component
public class AuthCheckAspect {

    private static final AuthHelper<BaseLoginUser> authHelper = new AuthHelper<>(BaseLoginUser.class);

    private static final String POINTCUT_SIGN =
            "@annotation(com.geeguo.ebuilder.core.security.annotation.RequiresLogin) || " +
            "@annotation(com.geeguo.ebuilder.core.security.annotation.RequiresRoles) || " +
            "@annotation(com.geeguo.ebuilder.core.security.annotation.RequiresPermissions)";

    @Pointcut(POINTCUT_SIGN)
    public void pointcut() {
    	
    }

    @Around("pointcut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        // 注解鉴权
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        checkMethodAnnotation(signature.getMethod());
        // 执行原有逻辑
        return joinPoint.proceed();
    }

    /**
     * 对一个Method对象进行注解检查
     */
    public void checkMethodAnnotation(Method method) {
        // 校验 @RequiresLogin 注解
        RequiresLogin requiresLogin = method.getAnnotation(RequiresLogin.class);
        if (requiresLogin != null) {
            authHelper.checkLogin();
        }
        
        // 校验 @RequiresRoles 注解
        RequiresRoles requiresRoles = method.getAnnotation(RequiresRoles.class);
        if (requiresRoles != null) {
            authHelper.checkRole(requiresRoles);
        }
        
        // 校验 @RequiresPermissions 注解
        RequiresPermissions requiresPermissions = method.getAnnotation(RequiresPermissions.class);
        if (requiresPermissions != null) {
            authHelper.checkPermission(requiresPermissions);
        }
    }
}